package com.ep.general;

import java.io.Serializable;
import java.math.BigInteger;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;

public class GeneralClassMdt<T> extends GeneralMdt {

	private Class<T> persistentClass;

	public GeneralClassMdt(Class<T> persistentClass) {
		this.persistentClass = persistentClass;
	}

	public Class<T> getPersistentClass() {
		return persistentClass;
	}

	@SuppressWarnings("unchecked")
	public T get(Serializable id) {
		try {
			getSession().beginTransaction();
			T result = (T) getSession().get(persistentClass, id);
			getSession().getTransaction().commit();

			return result;

		} catch (HibernateException e) {
			logger.error("Get class: " + getPersistentClass() + " id: " + id);
			logger.error(e.toString());
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	public T get(int id) {
		getSession().beginTransaction();
		T result = (T) getSession().get(persistentClass, id);
		getSession().getTransaction().commit();

		return result;
	}

	public int getNextSequenceValue(String sequenceName) {
		String sql = "SELECT nextval( ? )";
		getSession().beginTransaction();
		SQLQuery query = getSession().createSQLQuery(sql);
		query.setString(0, sequenceName);

		int result = ((BigInteger) query.uniqueResult()).intValue();

		getSession().getTransaction().commit();

		return result;
	}

	public T makePersistent(T entity) {
		getSession().beginTransaction();
		getSession().saveOrUpdate(entity);
		getSession().getTransaction().commit();

		return entity;
	}

	public Serializable save(T entity) {
		getSession().beginTransaction();
		Serializable item = getSession().save(entity);
		getSession().getTransaction().commit();

		return item;
	}

	public void delete(T entity) {
		getSession().beginTransaction();
		getSession().delete(entity);
		getSession().getTransaction().commit();
	}

	public T merge(T entity) {
		getSession().beginTransaction();
		getSession().merge(entity);
		getSession().getTransaction().commit();
		return entity;
	}

	@SuppressWarnings("unchecked")
	public List<T> list(Criteria crit) {
		List<T> result = crit.list();
		getSession().getTransaction().commit();
		return result;
	}

	@SuppressWarnings("unchecked")
	public List<T> list(SQLQuery query) {
		List<T> result = query.list();
		getSession().getTransaction().commit();
		return result;
	}

	@SuppressWarnings("unchecked")
	public T uniqueResult(Criteria crit) {
		Object result = crit.uniqueResult();
		getSession().getTransaction().commit();
		return (T) result;
	}

	@SuppressWarnings("unchecked")
	public T uniqueResult(SQLQuery query) {
		Object result = query.uniqueResult();
		getSession().getTransaction().commit();
		return (T) result;
	}
}
